import { decompress, compress } from "./compress";
import { isFunction } from "./validate";
/**
 * 判断两个对象是否相等，这两个对象的值只能是数字或字符串
 * @param {*} obj1 对象
 * @param {*} obj2 对象
 */
export function objEqual(obj1, obj2) {
  const keysArr1 = Object.keys(obj1);
  const keysArr2 = Object.keys(obj2);
  if (keysArr1.length !== keysArr2.length) return false;
  if (keysArr1.length === 0 && keysArr2.length === 0) return true;
  return !keysArr1.some(key => obj1[key] != obj2[key])
}
/**
 * 根据name/params/query判断两个路由对象是否相等
 * @param {*} route1 路由对象
 * @param {*} route2 路由对象
 */
export const routeEqual = (route1, route2) => {
  const params1 = route1.params || {};
  const params2 = route2.params || {};
  const query1 = route1.query || {};
  const query2 = route2.query || {};
  return (route1.name === route2.name) && objEqual(params1, params2) && objEqual(query1, query2)
}
/**
 * 根据路由，返回路由标题
 * @param {*} item 路由内容
 */
export function showTitle(item) {
  if (!item.meta) return;
  let { title } = item.meta;
  if (!title) return item.name;
  return isFunction(title) ? title(item) : title;
}
/**
 * 压缩权限码
 * @param {string[]} permissions 权限清单
 * @returns {string}
 */
export function packagePermissions(permissions) {
  return compress(permissions.join());
}
/**
 * 解压权限码
 * @param {string} permissions 经过压缩的权限字符串
 * @returns {string[]}
 */
export function unPackagePermissions(permissions) {
  if (permissions) {
    return decompress(permissions).split(',')
  } else {
    return [];
  }
}
/**
 * 合并对象
 * @param {Object} source 原始对象
 * @param {Object} target 目标对象
 */
export function extend(source, target) {
  for (var key in target) {
    if (source.hasOwnProperty(key)) {
      if (Object.prototype.toString.call(source[key]) === '[object Object]') {
        extend(source[key], target[key]);
      }
    } else {
      source[key] = target[key]
    }
  }
  return source;
}
